package com.easylinkin.sm.permission.impl;

import com.easylinkin.sm.entity.Customer;
import com.easylinkin.sm.permission.jpa.JpaCustomerPermission;

import java.util.Objects;
import javax.persistence.criteria.Path;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import site.morn.boot.jpa.JpaPredicate;
import site.morn.framework.context.AccountContext;

/**
 * 客户权限实现
 *
 * <p>基于JPA实现
 *
 * @author majintao
 * @since1.0.0, 2019-10-17-17:05
 */
@Component
public class SimpleJpaCustomerPermission implements JpaCustomerPermission {

  private Long id;

  private String fieldName = "customerId";

  private Path path;

  @Override
  public JpaCustomerPermission foreignKey(String fieldName) {
    this.fieldName = fieldName;
    return this;
  }

  @Override
  public JpaCustomerPermission foreignKey(Path path) {
    this.path = path;
    return this;
  }

  @Override
  public <T> Specification<T> specification() {
    return (root, query, builder) -> {
      JpaPredicate predicate = new JpaPredicate(builder);
      if (!Objects.isNull(this.id)) {
        if (Objects.isNull(this.path)) {
          this.path = root.get(this.fieldName);
        }
        predicate.appendAnd(builder.equal(this.path, id));
      }
      return predicate.get();
    };
  }

  @Override
  public JpaCustomerPermission customer(Long id) {
    this.id = id;
    return this;
  }

  @Override
  public JpaCustomerPermission currentCustomer() {
    this.id = AccountContext.current(Customer.class).getId();
    return this;
  }
}
